<?php
// +----------------------------------------------------------------------
// | sfadmin - Suifeng Administration
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2020 http://suifeng.tech All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: suifeng <1787585212@qq.com>
// +----------------------------------------------------------------------

namespace suifeng\mvc\admin;

use suifeng\builder\ListBuilder;
use suifeng\builder\FormBuilder;
use suifeng\helper\ClassHelper;

abstract class ModelController extends AdminController
{

    /**
     * 模型名称，必填项。
     */
    protected $model_name;

    /**
     * 初始化控制器。
     */
    protected function _initialize()
    {
        parent::_initialize();
        $this->model_object = $this->_get_model_object();
        $this->model_title = $this->_get_model_property('model_title');
        $this->model_fields = $this->_get_model_property('model_fields');
        $this->key_field = $this->_get_model_property('key_field');
        $this->extra_wheres = $this->_get_model_property('extra_wheres');

        $this->list_fields = $this->_get_model_property('list_fields');
        $this->list_actions = $this->_get_model_property('list_actions');
        $this->list_buttons = $this->_get_model_property('list_buttons');
        $this->default_page_size = $this->_get_model_property('default_page_size');
        $this->default_sort = $this->_get_model_property('default_sort');
        $this->default_sort_field = $this->_get_model_property('default_sort_field');
        $this->default_sort_order = $this->_get_model_property('default_sort_order');
        $this->avail_sort_fields = $this->_get_model_property('avail_sort_fields');
        $this->avail_search_fields = $this->_get_model_property('avail_search_fileds');
        $this->avail_filter_fields = $this->_get_model_property('avail_filter_fields');
        $this->enable_search = $this->_get_model_property('enable_search');
        $this->enable_sort = $this->_get_model_property('enable_sort');
        $this->enable_filter = $this->_get_model_property('enable_filter');
        $this->enable_select = $this->_get_model_property('enable_select');
        $this->enable_page = $this->_get_model_property('enable_page');

        // 列表请求相关信息
        $this->list_wheres = array();
        $this->list_data = array();
        $this->list_count = 0;
        $this->page_number = 1;
        $this->page_size = $this->default_page_size;
        $this->sort_field = $this->default_sort_field;
        $this->sort_order = $this->default_sort_order;
        $this->search_word = '';
        $this->filter_params =  array();

        // 表单请求相关信息
    }

    /**
     * 列表。
     */
    public function index()
    {
        $this->_handle_list_init();
        $this->_handle_list_data();

        $list_object = $this->_create_model_list();
        $this->_handle_list_object($list_object);

        $content = $list_object->render_html();
        $content = $this->_handle_list_content($content);

        $tpl_name = 'admin@public/model_list';
        $tpl_vars['content'] = $content;
        $tpl_vars['title'] = $this->model_title . '列表';
        $this->display($tpl_name, $tpl_vars);
    }

    /**
     * 创建
     */
    public function create()
    {
        $this->model_form = $this->_create_model_form();
        $this->_handle_form_init();

        $this->model_form->original_data = $this->_get_default_data_array();
        $this->_handle_form_original();

        if (request()->isPost()) {
            $merged_data = array_merge($this->model_form->original_data, $_POST);
            $this->model_form->init_submitted_data($merged_data);
        } else {
            $this->model_form->init_submitted_data($this->model_form->original_data);
        }

        $this->_handle_form_ready();

        if (request()->isPost()) {
            $this->model_form->validate();
            $this->_handle_form_validate();

            if ($this->model_form->is_valid) {
                $this->_handle_form_before_insert();
                $this->_handle_form_before_save();
                $submitted_data = $this->model_form->submitted_data;

                if ($this->model_object->insert($submitted_data)) {
                    $this->_handle_form_after_insert();
                    $this->_handle_form_after_save();
                    $this->success('新增成功', url('index'));
                } else {
                    $this->error($this->model_objec->getError());
                }
            }
        }

        $this->content = $this->model_form->render_html();
        $this->_handle_form_content();

        $this->tpl_name = 'admin@public/model_form';
        $this->tpl_vars['content'] = $this->content;
        $this->tpl_vars['meta_title'] = '新增' . $this->_get_model_title();
        $this->tpl_vars['title'] = '新增' . $this->_get_model_title();
        $this->_handle_template_display();
    }

    /**
     * 修改
     */
    public function modify()
    {
        $this->model_form = $this->_create_model_form();
        $this->_handle_form_init();

        $where_map[$this->model_form->key_field] = $this->model_form->key_value;
        $this->model_form->original_data = $this->model_object->where($where_map)->findOrFail()->getData();
        $this->_handle_form_original();

        if (request()->isPost()) {
            $merged_data = array_merge($this->model_form->original_data, $_POST);
            $this->model_form->init_submitted_data($merged_data);
        } else {
            $this->model_form->init_submitted_data($this->model_form->original_data);
        }

        $this->_handle_form_ready();

        if (request()->isPost()) {
            $this->model_form->validate();
            $this->_handle_form_validate();

            if ($this->model_form->is_valid) {
                $this->_handle_form_before_update();
                $this->_handle_form_before_save();
                $submitted_data = $this->model_form->submitted_data;

                if ($this->model_object->update($submitted_data, $where_map)) {
                    $this->_handle_form_after_update();
                    $this->_handle_form_after_save();
                    $this->success('修改成功', url('index'));
                } else {
                    $this->error($this->model_objec->getError());
                }
            }
        }

        $this->content = $this->model_form->render_html();
        $this->_handle_form_content();

        $title = '修改' . $this->_get_model_title();
        $summary_info = $this->model_object->summary_info($this->model_form->original_data);
        if ($summary_info) {
            $title .= ' - ' . $summary_info;
        }

        $this->tpl_name = 'admin@public/model_form';
        $this->tpl_vars['content'] = $this->content;
        $this->tpl_vars['meta_title'] = $title;
        $this->tpl_vars['title'] = $title;
        $this->_handle_template_display();
    }

    /**
     * 启用。
     */
    public function enable()
    {
        $model_object = $this->_get_model_object();

        $key_field = $this->_get_key_field();
        $id_list = input($key_field . '/a');

        $where_map[$key_field] = array('in', $id_list);
        $this->model_list = $model_object->where($where_map)->selectOrFail();
        $this->_handle_model_list();

        $model_object->where($where_map)->update(['status' => STATUS_ENABLED]);
        $this->success('启用成功', url('index'));
    }

    /**
     * 禁用。
     */
    public function disable()
    {
        $model_object = $this->_get_model_object();

        $key_field = $this->_get_key_field();
        $id_list = input($key_field . '/a');

        $where_map[$key_field] = array('in', $id_list);
        $this->model_list = $model_object->where($where_map)->selectOrFail();
        $this->_handle_model_list();

        $model_object->where($where_map)->update(['status' => STATUS_DISABLED]);
        $this->success('禁用成功', url('index'));
    }

    /**
     * 魔术方法，支持动态的参数获取。
     *
     * @param unknown $name
     * @param unknown $args
     * @throws \Exception
     * @return \app\common\controller\unknown|\suifeng\utils\NULL|mixed|string
     */
    public function __call($name, $args)
    {
        if (substr($name, 0, 5) == '_get_') {
            $property = substr($name, 5);
            if (count($args) > 0) {
                $default = array_shift($args);
            } else {
                $default = null;
            }
            return $this->_get_model_property($property, $default);
        } else {
            throw new \Exception('Invalid method name:' . $name);
        }
    }

    /**
     * 获取模型对象，如果不存在，会自动创建。
     *
     * @return \think\Model
     */
    protected function _get_model_object()
    {
        if (empty($this->model_object)) {
            $this->model_object = model($this->model_name);
        }
        return $this->model_object;
    }

    /**
     * 返回模型对象数据。
     *
     * @return array|unknown
     */
    protected function _get_model_data($key_value)
    {
        $model_object = $this->_get_model_object();
        $key_field = $this->model_object->getPk();
        $where[$key_field] = $key_value;
        return $model_object->where($where)->findOrFail()->getData();
    }

    /**
     * 获取属性值，先检查控制器，再检查模型对象，最后返回默认值。
     *
     * @param unknown $property
     * @param unknown $default
     * @return unknown|\suifeng\utils\NULL|mixed|string
     */
    protected function _get_model_property($property, $default = null)
    {
        if (isset($this->$property) && $this->$property !== null) {
            return $this->$property;
        }

        $property_value = $this->model_object->get_model_property($property);
        if ($property_value !== null) {
            return $property_value;
        }

        return $default;
    }

    /**
     * 返回字段相关信息。
     *
     * @param unknown $name
     * @return array
     */
    protected function _get_field_info($fied_name)
    {
        $model_fields = $this->_get_model_fields();
        if (isset($model_fields[$fied_name])) {
            return $model_fields[$fied_name];
        } else {
            return array();
        }
    }

//     /**
//      * 获取属性值，先检查控制器，再检查模型对象，最后返回默认值。
//      *
//      * @param unknown $property
//      * @param unknown $default
//      * @return unknown|\suifeng\utils\NULL|mixed|string
//      */
//     protected function _get_property_value($property, $default = null)
//     {
//         if (isset($this->$property) && $this->$property !== null) {
//             return $this->$property;
//         }

//         $model_object = $this->_get_model_object();

//         $property_value = $model_object->get_model_property($property);
//         if ($property_value !== null) {
//             return $property_value;
//         }

//         if (isset($model_object->$property) && $model_object->$property !== null) {
//             return $model_object->$property;
//         }

//         return $default;
//     }

//     /**
//      * 返回模型对象默认数据。
//      *
//      * @return array|unknown
//      */
//     protected function _get_model_default()
//     {
//         $default_data = array();
//         foreach ($this->_get_model_fields() as $field_name => $field_info) {
//             $default_data = $field_info['default'];
//         }
//         return $default_data;
//     }

//     /**
//      * 获取模型标题信息。
//      *
//      * @return string
//      */
//     protected function _get_model_title()
//     {
//         $property_value = $this->_get_property_value('model_title');
//         if (empty($property_value)) {
//             $model_object = $this->_get_model_object();
//             $property_value = StrUtil::friendly_text($model_object);
//         }
//         return $property_value;
//     }

//     /**
//      * 返回model_fields属性。
//      *
//      * @return array
//      */
//     protected function _get_model_fields()
//     {
//         if (isset($this->_cache_model_fields)) {
//             return $this->_cache_model_fields;
//         }

//         $model_fields = $this->_get_property_value('model_fields', array());

//         foreach ($model_fields as $field_name => $field_info) {
//             if (empty($field_info['dbtype'])) {
//                 $field_info['dbtype'] = 'string';
//             }

//             if (! isset($field_info['default'])) {
//                 $field_info['default'] = ClassUtil::default_value($field_info['dbtype']);
//             }

//             if (empty($field_info['title'])) {
//                 if (isset($field_info['label'])) {
//                     $field_info['title'] = $field_info['label'];
//                 } else {
//                     $field_info['title'] = StrUtil::friendly_text($field_name);
//                 }
//             }

//             if (empty($field_info['label'])) {
//                 if (isset($field_info['title'])) {
//                     $field_info['label'] = $field_info['title'];
//                 } else {
//                     $field_info['label'] = StrUtil::friendly_text($field_name);
//                 }
//             }

//             if (empty($field_info['control'])) {
//                 if (isset($field_info['display'])) {
//                     $field_info['control'] = $field_info['display'];
//                 } else if (isset($field_info['identity']) && $field_info['identity']) {
//                     $field_info['control'] = 'hidden';
//                 } else if (array_key_exists($field_name, $this->uneditable_field_names)) {
//                     $field_info['control'] = 'hidden';
//                 } else if (array_key_exists($field_info['dbtype'], $this->data_type_map)) {
//                     $field_info['control'] = $this->data_type_map[$field_info['dbtype']];
//                 } else {
//                     $field_info['control'] = 'text';
//                 }
//             }

//             if (empty($field_info['column'])) {
//                 if (isset($field_info['display'])) {
//                     $field_info['column'] = $field_info['display'];
//                 } else {
//                     $field_info['column'] = 'text';
//                 }
//             }

//             if (empty($field_info['rules'])) {
//                 $field_info['rules'] = array();
//             }

//             $clone_rules = $field_info['rules'];
//             $field_info['rules'] = array();
//             foreach ($clone_rules as $rule_type => $rule_config) {
//                 if (is_int($rule_type) && is_string($rule_config)) {
//                     $rule_config = ['rule' => $rule_config];
//                 } else if (is_string($rule_type) && is_string($rule_config)) {
//                     $rule_config = ['rule' => $rule_type, 'message' => $rule_config];
//                 } else {
//                     if (is_string($rule_type)) {
//                         $rule_config['rule'] = $rule_type;
//                     }
//                 }
//                 $field_info['rules'][] = $rule_config;
//             }

//             $default_rules = array();
//             if (isset($field_info['required']) && $field_info['required'] && !$this->_check_rule_exists($field_info['rules'], 'required')) {
//                 $default_rules[] = ['rule' => 'required'];
//             }
//             if ($field_info['dbtype'] == 'string' && isset($field_info['length']) && $field_info['length'] > 0 && !$this->_check_rule_exists($field_info['rules'], 'length')) {
//                 $default_rules[] = ['rule' => 'length', 'max' => intval($field_info['length'])];
//             }
//             if (isset($field_info['unique']) && $field_info['unique'] && !$this->_check_rule_exists($field_info['rules'], 'unique')) {
//                 $default_rules[] = ['rule' => 'unique'];
//             }
//             $field_info['rules'] = array_merge($default_rules, $field_info['rules']);

//             $this->_cache_model_fields[$field_name] = $field_info;
//         }

//         return $this->_cache_model_fields;
//     }

//     /**
//      * 检查指定的rule是否存在。
//      *
//      * @param unknown $rule_list
//      * @param unknown $check_rule
//      * @return boolean
//      */
//     protected function _check_rule_exists($rule_list, $check_rule)
//     {
//         foreach ($rule_list as $rule_config) {
//             if (isset($rule_config['rule']) && $rule_config['rule'] == $check_rule) {
//                 return true;
//             }
//         }
//         return false;
//     }



//     /**
//      * 返回extra_wheres属性。
//      *
//      * @return NULL|string
//      */
//     protected function _get_extra_wheres()
//     {
//         return $this->_get_property_value('extra_wheres', []);
//     }

//     /**
//      * 获取模型对象Pk属性。
//      *
//      * @return array
//      */
//     protected function _get_key_field()
//     {
//         return $this->_get_model_object()->getPk();
//     }

//     /**
//      * 返回default_sort_field属性。
//      *
//      * @return NULL|string
//      */
//     protected function _get_default_sort_field()
//     {
//         return $this->_get_property_value('default_sort_field');
//     }

//     /**
//      * 返回default_sort_order属性。
//      *
//      * @return NULL|string
//      */
//     protected function _get_default_sort_order()
//     {
//         return $this->_get_property_value('default_sort_order', 'asc');
//     }

//     /**
//      * 返回default_page_size属性。
//      *
//      * @return NULL|string
//      */
//     protected function _get_default_page_size()
//     {
//         return $this->_get_property_value('default_page_size', config('ADMIN_PAGE_ROWS'));
//     }

//     /**
//      * 返回avail_search_fields属性。
//      *
//      * @return NULL|string
//      */
//     protected function _get_avail_search_fields()
//     {
//         return $this->_get_property_value('avail_search_fields', []);
//     }

//     /**
//      * 返回avail_sort_fields属性。
//      *
//      * @return NULL|string
//      */
//     protected function _get_avail_sort_fields()
//     {
//         return $this->_get_property_value('avail_sort_fields', []);
//     }

//     /**
//      * 返回list_fields属性。
//      *
//      * @return NULL|string
//      */
//     protected function _get_list_fields()
//     {
//         $list_fields = $this->_get_property_value('list_fields');

//         if (empty($list_fields)) {
//             $list_fields = array_keys($this->_get_model_fields());
//         }

//         return $list_fields;
//     }

//     /**
//      * 返回list_actions属性。
//      *
//      * @return NULL|string
//      */
//     protected function _get_list_actions()
//     {
//         return $this->_get_property_value('list_actions', ['modify', 'delete']);
//     }

//     /**
//      * 返回list_buttons属性。
//      *
//      * @return NULL|string
//      */
//     protected function _get_list_buttons()
//     {
//         return $this->_get_property_value('list_buttons', ['create']);
//     }

//     /**
//      * 返回form_fields属性。
//      *
//      * @return NULL|string
//      */
//     protected function _get_form_fields()
//     {
//         $form_fields = $this->_get_property_value('form_fields');

//         if (empty($form_fields)) {
//             foreach ($this->_get_model_fields() as $field_name => $field_info) {
//                 if (isset($field_info['identity']) && $field_info['identity']) {
//                     continue;
//                 } else if (in_array($field_name, $this->uneditable_field_names)) {
//                     continue;
//                 } else {
//                     $form_fields[] = $field_name;
//                 }
//             }
//         }

//         return $form_fields;
//     }

//     /**
//      * 返回form_layout属性。
//      *
//      * @return NULL|string
//      */
//     protected function _get_form_layout()
//     {
//         return $this->_get_property_value('form_layout', null);
//     }

    /**
     * 创建表单对象。
     *
     * @return \suifeng\html\FormBuilder
     */
    protected function _create_model_form()
    {
        $model_object = $this->_get_model_object();

        $model_form = new FormBuilder($model_object);
        $model_form->model_object = $model_object;
        $model_form->key_field = $this->_get_key_field();
        $model_form->key_value = input($model_form->key_field);

        foreach ($this->_get_form_fields() as $name => $config) {
            if (is_string($config)) {
                $name = $config;
                $config = [];
            }

            $field_info = $this->_get_field_info($name);
            $config = array_merge($field_info, (array) $config);

            $type = $config['control'];
            $model_form->add_control($name, $type, $config);
        }

        $model_form->layout = $this->_get_form_layout();

        return $model_form;
    }

    /**
     * 创建列表对象。
     *
     * @return \suifeng\html\ListBuilder
     */
    protected function _create_model_list()
    {
        $model_list = new ListBuilder();
        $model_list->controller = $this;
        $model_list->model_object = $this->model_object;
        $model_list->key_field = $this->key_field;
        $model_list->avail_sort_fields = $this->avail_sort_fields;
        $model_list->avail_search_fields = $this->avail_search_fields;
        $model_list->avail_filter_fields = $this->avail_filter_fields;
        $model_list->enable_search = $this->enable_search;
        $model_list->enable_sort = $this->enable_sort;
        $model_list->enable_filter = $this->enable_filter;
        $model_list->enable_page = $this->enable_page;;
        $model_list->enable_select = $this->enable_select;
        $model_list->page_url = $this->_url('index', ['s_page' => '[page]']);

        $model_list->page_size = $this->page_size;
        $model_list->page_number = $this->page_number;
        $model_list->sort_field = $this->sort_field;
        $model_list->sort_order = $this->sort_order;
        $model_list->search_word = $this->search_word;
        $model_list->filter_params = $this->filter_params;

        $model_list->rows_count = $this->list_count;
        $model_list->data_list = $this->list_data;

        foreach ($this->list_fields as $field => $config) {
            if (is_string($config)) {
                $config = ['field' => $config];
            } else if (is_string($field)) {
                $config['field'] = $field;
            }

            if (isset($config['field'])) {
                $field_info = $this->_get_field_info($config['field']);
                $config = array_merge($field_info, (array) $config);

                if (empty($config['type']) && isset($config['column'])) {
                    $config['type'] = $config['column'];
                }
            }

            $model_list->add_column($config);
        }

        foreach ($this->list_actions as $type => $config) {
            if (is_string($config)) {
                $config = ['type' => $config];
            } else if (is_string($type)) {
                $config['type'] = $type;
            }
            $model_list->add_action((array) $config);
        }

        foreach ($this->list_buttons as $type => $config) {
            if (is_string($config)) {
                $config = ['type' => $config];
            } else if (is_string($type)) {
                $config['type'] = $type;
            }
            $model_list->add_button((array) $config);
        }

        return $model_list;
    }








    /**
     * 返回列表参数，列表参数以s_开头。
     *
     * @return NULL[]|unknown[]|mixed[]
     */
    protected function _get_list_params()
    {
        $params = array(
            'word'  => null,
            'page'  => null,
            'size'  => null,
            'sort'  => null,
            'order' => null,
        );

        $input = $this->request->param();

        if (isset($input['s_list'])) {
            $parts = explode(',', $input['s_list']);
            if (isset($parts[0]) && $parts[0]) {
                $params['page'] = $parts[0];
            }
            if (isset($parts[1]) && $parts[1]) {
                $params['size'] = $parts[1];
            }
            if (isset($parts[2]) && $parts[2]) {
                $params['sort'] = $parts[2];
            }
            if (isset($parts[3]) && $parts[3]) {
                $params['order'] = $parts[3];
            }
            unset($input['s_list']);
        }

        foreach ($input as $key => $value) {
            if (substr($key, 0, 2) == 's_') {
                $params[substr($key, 2)] = $value;
            }
        }

        return $params;
    }

    /**
     * 返回过滤参数，过滤参数以f_开头。
     *
     * @return array
     */
    protected function _get_filter_params()
    {
        $params = array();
        foreach ($this->request->param() as $key => $value) {
            if (substr($key, 0, 2) == 'f_') {
                $params[substr($key, 0, 2)] = $value;
            }
        }
        return $params;
    }

    /**
     * 返回URL地址。
     *
     * @param unknown $url
     * @param array $args
     * @return string
     */
    protected function _url($url, $args = [])
    {
        $list_params = $this->_get_list_params();
        $filter_params = $this->_get_filter_params();
        $query_params = array();

        foreach ($list_params as $name => $value) {
            if ($value !== null) {
                $query_params['s_' . $name] = $value;
            }
        }

        foreach ($filter_params as $name => $value) {
            $query_params['f_' . $name] = $value;
        }

        foreach ($args as $name => $value) {
            if (array_key_exists($name, $list_params)) {
                $query_params['s_' . $name] = $value;
            } else if (array_key_exists($name, $filter_params)) {
                $query_params['f_' . $name] = $value;
            } else {
                $query_params[$name] = $value;
            }
        }

        return url($url, $query_params);
    }

//     /**
//      * 加载列表数据。
//      *
//      * @param unknown $model_list
//      */
//     protected function _load_list_data($model_list)
//     {
//         $list_params = $this->_get_list_params();
//         $filter_params = $this->_get_filter_params();

//         $word = $list_params['word'] ? $list_params['word'] : '';
//         $page = $list_params['page'] ? $list_params['page'] : 1;
//         $size = $list_params['size'] ? $list_params['size'] : $this->_get_default_page_size();
//         $sort = $list_params['sort'] ? $list_params['sort'] : $this->_get_default_sort_field();
//         $order = $list_params['order'] ? $list_params['order'] : $this->_get_default_sort_order();

//         $where_map = $this->_get_extra_wheres([]);

//         $avail_search_fields = $this->_get_avail_search_fields();
//         if ($model_list->enable_search && $avail_search_fields && $word) {
//             $condition = array('like', '%' . $word . '%');
//             $where_map[implode('|', $avail_search_fields)] = $condition;
//         }

//         $model_list->rows_count = $model_list->model_object->where($where_map)->count();

//         $query = $model_list->model_object->where($where_map);
//         $query->page($page, $size);

//         if ($sort && $order) {
//             $query->order($sort . ' ' . $order);
//         }

//         $model_list->data_list = $query->select();
//     }

//     protected function _build_list_where_map()
//     {
//         $where_map = $this->model_list->extra_wheres;

//         if ($this->model_list->enable_search && $this->model_list->search_word) {
//             $condition = array('like', '%' . $this->model_list->search_word . '%');
//             $where_map[implode('|', $this->model_list->avail_search_fields)] = $condition;
//         }

//         return $where_map;
//     }





//     /**
//      * 定制模板参数。
//      */


//     /**
//      * 定制$model_list对象。
//      *
//      * @param unknown $model_list
//      */
//     protected function _custom_model_list($model_list) {}

//     /**
//      * 定制$model_form对象。
//      *
//      * @param unknown $model_form
//      */
//     protected function _custom_model_form($model_form) {}

//     /**
//      * 定制列表内容。
//      *
//      * @param unknown $model_list
//      */
//     protected function _custom_list_data($model_list) {}

//     /**
//      * 定制列表内容。
//      *
//      * @param unknown $content
//      */
//     protected function _custom_list_content(&$content) {}

//     /**
//      * 定制输出内容。
//      *
//      * @param unknown $content
//      */
//     protected function _custom_content(&$content) {}

//     protected function _handle_form_init_ready($model_form) {}
//     protected function _handle_form_data_ready($model_form) {}
//     protected function _handle_form_original_data(&$data) {}
//     protected function _handle_form_submitted_data(&$data) {}

//     protected function _handle_template_vars(&$vars) {}

//     /**
//      * 触发事件处理方法。
//      *
//      * @param unknown $event
//      * @param unknown $arg1
//      * @param unknown $arg2
//      * @param unknown $arg3
//      * @return unknown
//      */
//     protected function _trigger($event, &$arg1 = null, &$arg2 = null, &$arg3 = null)
//     {
//         $event_method = '_handle_' . $event;
//         if (method_exists($this, $event_method)) {
//             return $this->$event_method($arg1, $arg2, $arg3);
//         }
//     }



    protected function _handle_list_init()
    {
        $input = $this->request->param();

        if (isset($input['s_size'])) {
            $this->page_size = intval($input['s_size']);
        } else {
            $this->page_size = $this->default_page_size;
        }

        if (isset($input['s_page'])) {
            $this->page_number = intval($input['s_page']);
        } else {
            $this->page_number = 1;
        }

        if (isset($input['s_sort'])) {
            $this->sort_field = intval($input['s_sort']);
        } else {
            $this->sort_field = $this->default_sort_field;
        }

        if (isset($input['s_order'])) {
            $this->sort_order = intval($input['s_order']);
        } else {
            $this->sort_order= $this->default_sort_order;
        }

        if (isset($input['s_word'])) {
            $this->search_word = $input['s_word'];
        } else {
            $this->search_word = '';
        }

        $this->filter_params = array();
        foreach ($input as $key => $value) {
            if (substr($key, 0, 2) == 'f_') {
                $this->filter_params[substr($key, 2)] = $value;
            }
        }
    }

    protected function _handle_list_data()
    {
        $count_query = $this->model_object->db();
        $this->_set_list_query_where($count_query);
        $this->list_count = $count_query->count();

        $list_query = $this->model_object->db();
        $this->_set_list_query_where($list_query);
        $this->_set_list_query_page_and_order($list_query);
        $this->list_data = $list_query->select();
    }

    protected function _handle_list_object($list_object) {}

    protected function _handle_list_content($content)
    {
        return $content;
    }

    protected function _set_list_query_where($query)
    {
        $where_map = array();

        if ($this->extra_wheres) {
            $where_map = array_merge($where_map, $this->extra_wheres);
        }

        if ($this->list_wheres) {
            $where_map = array_merge($where_map, $this->list_wheres);
        }

        if ($this->enable_search && $this->search_word) {
            $condition = array('like', '%' . $this->search_word . '%');
            $where_map[implode('|', $this->avail_search_fields)] = $condition;
        }

        if ($where_map) {
            $query->where($where_map);
        }
    }

    protected function _set_list_query_page_and_order($query)
    {
        if ($this->enable_page) {
            $query->page($this->page_number, $this->page_size);
        }

        if ($this->enable_sort && $this->sort_field && $this->sort_order) {
            $query->order($this->sort_field . ' ' . $this->sort_order);
        } else if ($this->default_sort) {
            $query->order($this->default_sort);
        }
    }

    protected function _handle_form_init() {}
    protected function _handle_form_original() {}
    protected function _handle_form_ready() {}
    protected function _handle_form_content() {}

    protected function _handle_form_validate() {}
    protected function _handle_form_before_save() {}
    protected function _handle_form_after_save() {}
    protected function _handle_form_before_update() {}
    protected function _handle_form_after_update() {}
    protected function _handle_form_before_insert() {}
    protected function _handle_form_after_insert() {}
    protected function _handle_form_before_delete() {}
    protected function _handle_form_after_delete() {}
    protected function _handle_model_list() {}

//     /**
//      * 处理模板变量。
//      */
//     protected function _handle_template_vars() {}

//     /**
//      * 输出模板内容。
//      */
//     protected function _handle_template_display()
//     {
//         if (empty($this->tpl_name)) {
//             $this->tpl_name = 'admin@public/main';
//         }

// //         // 检查有没有设置标题title
// //         if (empty($this->tpl_vars['title'])) {
// //             $ref_method = new \ReflectionAnnotatedMethod($this, request()->action());
// //             if ($ref_method->hasAnnotation('Title')) {
// //                 $title = $ref_method->getAnnotation('Title')->value;
// //             } else {
// //                 $title = ucfirst(request()->action());
// //             }
// //             $this->tpl_vars['title'] = $title;
// //         }

// //         if (empty($this->tpl_vars['meta_title'])) {
// //             $this->tpl_vars['meta_title'] = $this->tpl_vars['title'];
// //         }

//         $this->assign($this->tpl_vars);
//         $this->display($this->tpl_name);
//     }

    protected function _handle_template_display()
    {
        if (empty($this->tpl_name)) {
            $this->tpl_name = 'admin@public/main';
        }

        $this->assign($this->tpl_vars);
        $this->display($this->tpl_name);
    }


    /**
     * 删除
     */
    public function delete()
    {
        //
    }
}
